﻿using MediatR;
using RBAC_Class.Read.API.Application.Command.Permissions;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;

namespace RBAC_Class.Read.API.Application.CommandHandler.Permissions
{
    public class PermissionQueryCommandHandler:IRequestHandler<PermissionQueryCommand,APIResult<APIPaging<List<Permission>>>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly ILogger<PermissionQueryCommandHandler> logger;

        public PermissionQueryCommandHandler(IBaseRepository<Permission> permissionRep, ILogger<PermissionQueryCommandHandler> logger)
        {
            this.permissionRep = permissionRep;
            this.logger = logger;
        }

        public Task<APIResult<APIPaging<List<Permission>>>> Handle(PermissionQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = permissionRep.GetAll().Where(x => x.IsDelete == false);
                if (!string.IsNullOrEmpty(request.PermissionName))
                {
                    list = list.Where(x => x.PermissionName.Contains(request.PermissionName));
                }
                var totalCount = list.Count();
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list = list.OrderBy(x => x.PermissionID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                return Task.FromResult(new APIResult<APIPaging<List<Permission>>>
                {
                    Code = ResultCode.Success,
                    Message = "查询成功",
                    Data = new APIPaging<List<Permission>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = list.ToList()
                    }
                });
            }
            catch (Exception ex)
            {
                logger.LogError("查询出错", ex);
                throw;
            }
            
        }
    }
}
